package shipment

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/types/order"

	"github.com/friendsofgo/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateOrderShipmentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateOrderShipmentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateOrderShipmentLogic {
	return &BackendUpdateOrderShipmentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: orderShipment
func (l *BackendUpdateOrderShipmentLogic) BackendUpdateOrderShipment(in *order.OrderShipmentInfo) (*order.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}
	var filterMap = map[string]map[string][]any{}
	if in.Id != nil && *in.Id > 0 {
		filterMap[model.OrderShipmentColumns.OrderShipmentID] = map[string][]any{
			"equalTo": {*in.Id},
		}
	}
	//if in.OrderId != nil && *in.OrderId > 0 {
	//	filterMap[model.OrderShipmentColumns.OrderID] = map[string][]any{
	//		"equalTo": {*in.OrderId},
	//	}
	//}
	list, _, err := l.svcCtx.Order.GetShipmentList(l.ctx, model.M{}, -1, filterMap)
	if len(list) == 0 {
		logx.Infof("BackendUpdateOrderShipment err: Shipment list empty")
		return nil, errors.New("BackendUpdateOrderShipment err: Shipment list empty")
	}
	shipment := list[0]
	if in.Status != nil {
		shipment.Status = uint8(*in.Status)
	}
	if in.Name != nil && len(strings.TrimSpace(*in.Name)) > 0 {
		shipment.Name = *in.Name
	}
	if in.Code != nil && len(strings.TrimSpace(*in.Code)) > 0 {
		shipment.Code = *in.Code
	}
	if in.No != nil && len(strings.TrimSpace(*in.No)) > 0 {
		shipment.No = *in.No
	}
	shipment.UpdatedAt = time.Now()
	err = l.svcCtx.Order.UpdateShipment(l.ctx, nil, shipment)
	if err != nil {
		logx.Infof("BackendUpdateOrderShipment UpdateShipment err:%+v", err)
		return nil, err
	}
	return &order.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
